﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace System.IO
{
    /// <summary>
    /// StreamExtension
    /// </summary>
    public static partial class StreamExtension
    {
        /// <summary>
        /// 读取当前流
        /// </summary>
        /// <param name="this"></param>
        /// <returns>返回流内容</returns>
        public static string ReadToEnd(this Stream @this)
        {
            using (var reader = new StreamReader(@this, Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
        /// <summary>
        /// 读取当前流
        /// </summary>
        /// <param name="this"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string ReadToEnd(this Stream @this,Encoding encoding)
        {
            using (var reader = new StreamReader(@this, encoding))
            {
                return reader.ReadToEnd();
            }
        }
        /// <summary>
        /// Stream转byte数组
        /// </summary>
        /// <param name="this"></param>
        /// <returns></returns>
        public static byte[] ToByteArray(this Stream @this)
        {
            using (var ms = new MemoryStream())
            {
                @this.CopyTo(ms);
                return ms.ToArray();
            }
        }
        /// <summary>
        /// 计算Stream的MD5
        /// </summary>
        /// <param name="this"></param>
        /// <returns></returns>
        public static string MD5(this Stream @this)
        {
            using (var md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] hashBytes = md5.ComputeHash(@this);
                return hashBytes.ToHexString();
            }
        }
    }
}
